<?php

class SiteCommand extends CConsoleCommand {

    public $categoryUrls = array(
        'tv' => 'http://market.yandex.ru/guru.xml?CMD=-RR%3D0%2C0%2C0%2C0-VIS%3D8070-CAT_ID%3D108206-EXC%3D1-PG%3D10&hid=90639',
        'dvd' => 'http://market.yandex.ru/guru.xml?CMD=-RR%3D0%2C0%2C0%2C0-VIS%3D8070-CAT_ID%3D140982-EXC%3D1-PG%3D10&hid=90633',
        'photo_camera' => 'http://market.yandex.ru/guru.xml?CMD=-RR%3D9%2C0%2C0%2C0-VIS%3D8070-CAT_ID%3D100514-EXC%3D1-PG%3D10&hid=91148',
        'mp3_player' => 'http://market.yandex.ru/guru.xml?CMD=-RR%3D9%2C0%2C0%2C0-VIS%3D8070-CAT_ID%3D137555-EXC%3D1-PG%3D10&hid=90560',
        'eBooks' => 'http://market.yandex.ru/guru.xml?CMD=-RR%3D0%2C0%2C0%2C0-VIS%3D8070-CAT_ID%3D2666443-EXC%3D1-PG%3D10&hid=2417247',
        'gps' => 'http://market.yandex.ru/guru.xml?CMD=-RR%3D9%2C0%2C0%2C0-VIS%3D8070-CAT_ID%3D971072-EXC%3D1-PG%3D10&hid=294661',
        'radiotelephones' => 'http://market.yandex.ru/guru.xml?CMD=-RR%3D9%2C0%2C0%2C0-VIS%3D8070-CAT_ID%3D101467-EXC%3D1-PG%3D10&hid=91464',
        'bluetooth' => 'http://market.yandex.ru/guru.xml?CMD=-RR%3D0%2C0%2C0%2C0-VIS%3D8070-CAT_ID%3D938245-EXC%3D1-PG%3D10&hid=418706',
        'mobile_phones' => 'http://market.yandex.ru/guru.xml?CMD=-RR%3D9%2C0%2C0%2C0-VIS%3D8070-CAT_ID%3D160043-EXC%3D1-PG%3D10&hid=91491',
        'sofa' => 'http://market.yandex.ru/search.xml?hid=7286125',
        'cupboard' => 'http://market.yandex.ru/search.xml?hid=90675',
        'tire' => 'http://market.yandex.ru/guru.xml?CMD=-RR%3D0%2C0%2C0%2C0-VIS%3D8070-CAT_ID%3D109743-EXC%3D1-PG%3D10&hid=90490',
        'wheel' => 'http://market.yandex.ru/guru.xml?CMD=-RR%3D0%2C0%2C0%2C0-VIS%3D8070-CAT_ID%3D922145-EXC%3D1-PG%3D10&hid=166068',
        'unit' => 'http://market.yandex.ru/guru.xml?CMD=-RR%3D9%2C0%2C0%2C0-VIS%3D8070-CAT_ID%3D105384-EXC%3D1-PG%3D10&hid=90404',
        'fridge' => 'http://market.yandex.ru/guru.xml?CMD=-RR%3D9%2C0%2C0%2C0-VIS%3D8070-CAT_ID%3D107500-EXC%3D1-PG%3D10&hid=90594',
        'vacuum_cleaner' => 'http://market.yandex.ru/guru.xml?CMD=-RR%3D0%2C0%2C0%2C0-VIS%3D8070-CAT_ID%3D176217-EXC%3D1-PG%3D10&hid=90564',
        'washing_machine' => 'http://market.yandex.ru/guru.xml?CMD=-RR%3D9%2C0%2C0%2C0-VIS%3D8070-CAT_ID%3D109012-EXC%3D1-PG%3D10&hid=90566',
        'microwaves' => 'http://market.yandex.ru/guru.xml?CMD=-RR%3D9%2C0%2C0%2C0-VIS%3D8070-CAT_ID%3D106643-EXC%3D1-PG%3D10&hid=90595',
        'multicooking' => 'http://market.yandex.ru/guru.xml?CMD=-RR%3D0%2C0%2C0%2C0-VIS%3D8070-CAT_ID%3D6161840-EXC%3D1-PG%3D10&hid=4954975',
        'conditioner' => 'http://market.yandex.ru/guru.xml?CMD=-RR%3D5%2C0%2C0%2C0-VIS%3D8070-CAT_ID%3D141694-EXC%3D1-PG%3D10&hid=90578',
        'sweaters' => 'http://market.yandex.ru/search?hid=7811897',
        'women_dress' => 'http://market.yandex.ru/search?hid=7811901',
        'man_dress' => 'http://market.yandex.ru/catalog?hid=7811877',
        'bag' => 'http://market.yandex.ru/search?hid=7812201',
        '' => '',
    );
    public $urls = array('http://market.yandex.ru/', 'http://market.yandex.ru/catalogmodels.xml?CAT_ID=140982&hid=90633', 'http://market.yandex.ru/product/8471273/reviews?hid=90633', 'http://market.yandex.ru/user/prime-computers/reviews', 'http://market.yandex.ru/catalog?hid=7877999');

    public function actionBack() {
        $sql = "SELECT row_id, brand_title, model_new_title FROM models where model_new_title is not null";
        $rows = Yii::app()->db->getCommandBuilder()->createSqlCommand($sql)->queryAll();
        foreach ($rows as $row) {
            $title = str_replace('\&quot;', '', $row['model_new_title']);
            $sql = "update models SET model_new_title='{$title}' WHERE row_id={$row['row_id']};";
            Yii::app()->db->getCommandBuilder()->createSqlCommand($sql)->execute();
            echo date('d-m-Y H:i:s') . ' - ' . ": => " . $sql . "\r\n";
        }
    }

    public function actionRemoveBrand() {
        $sql = "SELECT row_id, brand_title, model_new_title FROM models where model_new_title is not null";
        $rows = Yii::app()->db->getCommandBuilder()->createSqlCommand($sql)->queryAll();
        foreach ($rows as $row) {
            $title = str_replace($row['brand_title'], '', $row['model_new_title']);
            $title = CHtml::encode($title);
            $sql = "update models SET model_new_title='{$title}' WHERE row_id={$row['row_id']};";
            Yii::app()->db->getCommandBuilder()->createSqlCommand($sql)->execute();
            echo date('d-m-Y H:i:s') . ' - ' . ": => " . $sql . "\r\n";
        }
    }

    public function actionParent() {
//        set_time_limit(0);
//        ini_set("memory_limit", '1024M');
        $sql = "SELECT row_id, model_new_title FROM models where is_active =1 order by cat_id, brand_id, model_new_title";
        $rows = Yii::app()->db->getCommandBuilder()->createSqlCommand($sql)->queryAll();
        foreach ($rows as $row) {
            if (!isset($old) || strtoupper($old['model_new_title']) != strtoupper($row['model_new_title'])) {
                Yii::app()->db->getCommandBuilder()->createSqlCommand("update models SET is_parent='parent' WHERE row_id={$row['row_id']};")->execute();
            } else if (isset($old) && strtoupper($old['model_new_title']) == strtoupper($row['model_new_title'])) {
                Yii::app()->db->getCommandBuilder()->createSqlCommand("update models SET is_parent='{$old['row_id']}' WHERE row_id={$row['row_id']};")->execute();
            }
            $old = $row;
            print_r($old);
        }
    }

    public function actionRep() {
        $value = array(' 16Gb', ' 32Gb',
            ' 64Gb', ' 8Gb', ' 4Gb',
            ' 128Gb', ' 2Gb', ' 8Gb',
            ' 160Gb', ' 4Gb', ' 1Gb',
            ' 64Gb', ' 256Gb', ' 512Mb',
            ' 256Mb', ' 128Mb', ' 0Gb',
            ' RAM', 'Dual Sim', ' DG',
            ' 2Gb', 'Luxury Edition',
            ' Yandex', '2Gb Ram',
            '768Mb Ram',
            '1Gb Ram',
            ' DDR3', ' eMMC', ' 3G', ' SSD', ' DOS', ' DDR2', ' RAM',
            ' i5', ' i3', ' dock', ' keyboard',
            ' 4G', '+', 'Wi-Fi', 'Cellular', 'dock', 'i7',
            'keyboard', 'LTE', ' 3G', ' LTE', 'Win7',
            ' HP', 'IntelAtom', 'Z690', 'n2600',
            'AMD', 'Z-60', 'Core', 'Intel',
            '1.5GHz', 'Black', 'White',
            ' 253', ' iRu', ' eMMC', ' SSD',
            ' DOS', ' DDR2', ' RAM',
            ' ROM', ' 279', 'Microsoft',
            'Touch Cover', '+ Yota', 'Android 4.0',
            'Android 3.2', '32 HDD',
            '50 HDD', '75 HDD', '\'', '"'
        );
        $sql = 'SELECT model_title, row_id FROM models';
        $models = Yii::app()->db->getCommandBuilder()->createSqlCommand($sql)->queryAll();
//        print_r($models);exit;
        foreach ($models as $model) {
            $title = trim(str_replace($value, '', $model['model_title']));
            $sql = 'UPDATE models SET model_new_title = \'' . $title . '\' WHERE row_id = ' . $model['row_id'];
            echo date('d-m-Y H:i:s') . ' - ' . ": => " . $sql . "\r\n";
            Yii::app()->db->getCommandBuilder()->createSqlCommand($sql)->execute();
        }
    }

    public function actionDisabled() {
        $disableds = array(157, 160, 163, 164, 165, 168, 169, 171, 176, 180, 183, 184, 185, 187, 193, 189, 194, 195, 190, 197, 198, 199, 200, 202, 203, 204, 210, 211, 212, 215, 216, 217, 219, 221, 222, 226, 230, 225, 234, 249, 248, 238, 250, 251, 245, 239, 240, 247, 252, 254, 255, 256, 257, 258, 260, 261, 262, 267, 269, 265, 270, 273, 274, 275, 271, 276, 277, 278, 280, 281, 283, 284, 286, 288, 289, 290, 292, 293, 294, 295, 297, 298, 296, 300, 301, 302, 305, 309, 310, 312, 318, 319, 320, 321, 322, 323, 336, 335, 331, 339, 340, 332, 342, 343, 344, 347, 348, 350, 352, 353, 355, 346, 358, 359, 362, 363, 366, 367);
        $sql = 'UPDATE models SET is_active = 0 WHERE brand_id IN (' . implode(',', $disableds) . ')';
        echo date('d-m-Y H:i:s') . ' - ' . ": => " . $sql . "\r\n";
        Yii::app()->db->getCommandBuilder()->createSqlCommand($sql)->execute();
    }

    public function actionReplace() {

        $replaces[11] = array('16Gb', '32Gb', '64Gb', '8Gb');
        $replaces[4] = array('16Gb', '32Gb', '64Gb', '8Gb');
        $replaces[57] = array('768Mb Ram', '1Gb Ram');
        $replaces[55] = array('Dual Sim', '16Gb', '32Gb');
        $replaces[58] = array('Yandex', '2Gb Ram');
        $replaces[71] = array('16Gb', '32Gb', '64Gb', '8Gb', '4Gb');
        $replaces[70] = array('16Gb', '32Gb', '64Gb', '8Gb', '4Gb');
        $replaces[77] = array('16Gb', '32Gb', '64Gb', '8Gb', '4Gb', '128Gb');
        $replaces[80] = array('16Gb', '32Gb', '64Gb', '8Gb', '4Gb', '128Gb', 'Dual Sim', 'DG', '2Gb', 'Luxury Edition');
        $replaces[84] = array('16Gb', '32Gb', '64Gb', '8Gb', '4Gb', '128Gb', 'Dual Sim');
        $replaces[86] = array('16Gb', '32Gb', '64Gb', '8Gb', '4Gb', '128Gb');
        $replaces[111] = array('16Gb', '32Gb', '64Gb', '8Gb', '4Gb', '128Gb');
        $replaces[147] = array('16Gb', '32Gb', '64Gb', '8Gb', '4Gb', '128Gb');
        $replaces[153] = array('16Gb', '32Gb', '64Gb', '8Gb', '4Gb', '128Gb', 'RAM');
        $disableds = '';

        foreach ($replaces as $key => $value) {
//          $sql = 'UPDATE models SET title = \'' . $title . '\' WHERE id = ' . $key;
            $sql = 'SELECT model_title, id FROM models WHERE brand_id = \'' . $key . '\'';
            $models = Yii::app()->db->getCommandBuilder()->createSqlCommand($sql)->queryAll();
            foreach ($models as $model) {
                $title = trim(str_replace($value, '', $model['model_title']));
                $sql = 'UPDATE models SET title = \'' . $title . '\' WHERE id = ' . $model['id'];
                echo date('d-m-Y H:i:s') . ' - ' . ": => " . $sql . "\r\n";
                Yii::app()->db->getCommandBuilder()->createSqlCommand($sql)->execute();
            }
        }
    }

    public function actionGet() {
        set_time_limit(0);
        ini_set("memory_limit", '1024M');
        Yii::import('ext.phpQuery.phpQuery');
        $random = array_rand($this->urls);
//        print_r($random);exit;
        $a = 0;
        while (true) {
            $a++;
            $sql = 'select * from mb_model2yandex where "yandexTitle" is null LIMIT 1';
            $model = Yii::app()->db->getCommandBuilder()->createSqlCommand($sql)->queryAll();
            if (!$model)
                exit;
            $sql = 'UPDATE mb_model2yandex SET "yandexTitle"=\'\' WHERE "modelId" = ' . $model[0]['modelId'] . ' AND "yandexId" = ' . $model[0]['yandexId'];
            $c = Yii::app()->db->getCommandBuilder()->createSqlCommand($sql)->execute();

            $url = 'http://market.yandex.ru/model.xml?modelid=' . $model[0]['yandexId'];
            $output = Yii::app()->YandexData->get($url);
            $doc = phpQuery::newDocument($output);
            $name = trim(strip_tags(str_replace('новинка', '', pq($doc['h1.b-page-title__title'])->html())));
//            sleep(rand(0, 3));
//            Yii::app()->YandexData->get($this->urls[$random]);
            if (!empty($name) && strlen($name) > 4) {
                $sql = 'UPDATE mb_model2yandex SET "yandexTitle"=\'' . CHtml::encode($name) . '\' WHERE "modelId" = ' . $model[0]['modelId'] . ' AND "yandexId" = ' . $model[0]['yandexId'];
                $c = Yii::app()->db->getCommandBuilder()->createSqlCommand($sql)->execute();
//                 print_r($c);exit;
                echo $a . ' - ' . date('d-m-Y H:i:s') . ' - ' . ": => " . $sql . "\r\n";
            }
//            sleep(rand(0, 2));
//            Yii::app()->YandexData->get($this->urls[$random]);
        }
    }

    public function actionGetModels() {
        $catUrl = 'http://market.yandex.ru/catalogmodels.xml?CAT_ID=160043&hid=91491';
        set_time_limit(0);
        Yii::import('ext.phpQuery.phpQuery');
        $output = Yii::app()->YandexData->get($catUrl);
        $document = phpQuery::newDocument($output);
        $allBrandsUrl = pq($document['.b-category-pop-vendors a.black'])->attr('href');
        $output = Yii::app()->YandexData->get('http://market.yandex.ru' . $allBrandsUrl);
        $document = phpQuery::newDocument($output);
        foreach ($document['.b-vendor__item'] as $urls) {
            $brandUrls[] = pq($urls)->find('a.b-link')->attr('href');
        }
        print_r($brandUrls);
//        exit;
        foreach ($brandUrls as $k => $url) {
//            Yii::app()->session['brandUrl'] = 
            $file = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'tmp.txt';
            $prepared = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'prepared.txt';
            $urls_ = file_get_contents($prepared, true);
            $aUrls = json_decode($urls_, true);
            print_r($aUrls);
            if (!isset($aUrls[$url])) {
                $fp = fopen($file, 'w');
                $output = Yii::app()->YandexData->get('http://market.yandex.ru' . $url);
                fwrite($fp, $output);
                $document = phpQuery::newDocument($output);
                $pager = pq($document['a.b-pager__next'])->attr('href');
                if (!empty($pager)) {
                    $nextPage = '';
                    $flag = false;
                    $nextPage = pq($document['a.b-pager__next'])->attr('href');
                    while (!$flag) {
                        sleep(1);
                        $out = Yii::app()->YandexData->get('http://market.yandex.ru/' . $nextPage);
                        $d = phpQuery::newDocument($out);
                        $nextPage = pq($d['.b-pager span .b-pager__next'])->attr('href');
                        if (empty($nextPage))
                            $flag = true;
                        fwrite($fp, $out);
                    }
                }
                fclose($fp);
                $content = file_get_contents($file, true);
                $doc = phpQuery::newDocument($content);
                $category = trim(strip_tags(pq($doc['.b-breadcrumbs span a span'])->text()));
                $brand = trim(strip_tags(pq($doc['.b-breadcrumbs strong'])->text()));
                echo 'content=>' . $category . '-' . $brand . "\r\n";
                if (!isset($products))
                    $products = array();
                foreach ($doc['.page__b-offers__guru .b-offers'] as $key => $id) {
                    echo 'Product=>' . $key . "\r\n";
                    preg_match('@(.*)modelid=(\d+)(.*)@', pq($id)->find('.b-offers__pict a')->attr('href'), $content);
                    if (isset($content[2])) {
                        $featuresUrl = 'http://market.yandex.ru/compare.xml?hid=91491&CAT_ID=160043&CMD=-CMP=' . $content[2];
                        $output = Yii::app()->YandexData->get($featuresUrl);
                        $document = phpQuery::newDocument($output);
                        $features = array();
                        foreach ($document['.l-compare__body tr'] as $fs) {
                            $features[] = array('name' => strip_tags(pq($fs)->find('td.l-compare__name')->text()), 'value' => strip_tags(pq($fs)->find('td.l-compare__model')->text()));
                        }
                        $h1 = trim(pq($id)->find('.b-offers__desc .b-offers__title a')->text());
                        $products[] = array(
                            'mainImageUrl' => str_replace('&size=2', '', pq($id)->find('.b-offers__pict a img')->attr('src')),
                            'h1Title' => $h1,
                            'category' => $category,
                            'brand' => $brand,
                            'model' => mb_substr(str_replace($brand, '', $h1), 1, strlen($h1), 'utf-8'),
                            'yaId' => $content[2],
                            'yaPrice' => str_replace(" ", '', pq($id)->find('.b-prices__num')->text()),
                            'yaRating' => $key,
                            'features' => $features
                        );
                    }
                }

                $f = fopen($prepared, 'w');
                fwrite($f, $urls_);
                fwrite($f, json_encode(array($url => $k)));
                fclose($f);
            }
        }
        $models = json_encode($products);
        $file = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'models.txt';
        $fp = fopen($file, 'w');
        fwrite($fp, $models);
        fclose($fp);
        echo 'Finish';
//        print_r($products);
    }

    public function actionList() {
        $declaredClasses = get_declared_classes();
        foreach (glob(Yii::getPathOfAlias('application.controllers') . "/*Controller.php") as $controller) {
            $class = basename($controller, ".php");
            if (!in_array($class, $declaredClasses))
                Yii::import("application.controllers." . $class, true);
            $reflection = new ReflectionClass($class);
            $methods = $reflection->getMethods();
            $methods = get_class_methods($class);
            foreach ($methods as $method) {
                if (strpos($method, 'action') !== false && $method != 'actions') {
                    $actions[] = lcfirst(str_replace('Controller', '', $class)) . '/' . lcfirst(str_replace('action', '', $method));
                }
            }
        }
        print_r($actions);
    }

}
